package it.nola.soccer;

import it.nola.soccer.listener.TeamGoalItemListener;
import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class GoalEdit extends Activity {
    public DbAdapter getDbHelper() {
	return dbHelper;
    }

    public Spinner getPlayerSpinner() {
	return playerSpinner;
    }

    public long getCronaca() {
	return cronaca;
    }

    private DbAdapter dbHelper;
    private long cronaca;
    private Spinner playerSpinner;
    private Spinner teamSpinner;
    private EditText idGoalText;
    private EditText timeText;
    private CheckBox isOwnGoal;
    private Spinner halfSpinner;
    private ListView griglia;
    private TextView titleFormText;
    private CharSequence team1Name;
    private CharSequence team2Name;

    public void cancella(View view) {
	String rowId=idGoalText.getText().toString();
	if (!"".equals(rowId)) {
	    dbHelper.cancellaGoal(Long.parseLong(rowId));
	    Toast t=Toast.makeText(this, getString(R.string.goal_deleted), Toast.LENGTH_LONG);
	    t.show();
	    fillData();
	}
	halfSpinner.setSelection(0);
	teamSpinner.setSelection(0);
	playerSpinner.setSelection(0);
	isOwnGoal.setSelected(false);
	idGoalText.setText("");
	timeText.setText("");
	titleFormText.setText(getString(R.string.new_goal));
    }

    public void chiudi(View view) {
	finish();
    }

    private void fillData() {
	Cursor sc=dbHelper.cercaGoal(cronaca);
	String[] from=new String[]{DbConst.goals.KEY_TEAM, DbConst.goals.KEY_IS_AUTO, DbConst.goals.KEY_NAME_PLAYER,
	    DbConst.goals.KEY_HALF, DbConst.goals.KEY_MIN };
	int[] to=new int[]{R.id.team_goal_old, R.id.is_own_old, R.id.player_old, R.id.half_old, R.id.min_old };
	SimpleCursorAdapter goalAdapter=new SimpleCursorAdapter(this, R.layout.goal_row, sc, from, to);
	griglia.setAdapter(goalAdapter);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	// recupera i parametri passati tramite Intent
	Bundle extras=getIntent().getExtras();
	extras.keySet();
	if (extras!=null) {
	    cronaca=extras.getLong(DbConst.players.KEY_CRONACA);
	    team1Name=extras.getCharSequence(DbConst.HOME_TEAM.toString());
	    team2Name=extras.getCharSequence(DbConst.FOREIGN_TEAM.toString());
	}
	setTitle(getText(R.string.goals));
	setContentView(R.layout.goal_edit);
	dbHelper=new DbAdapter(this);
	dbHelper.open();
	prepareFields();
	fillData();
    }

    /**
     * Inizializza i campi presenti nella View
     */
    private void prepareFields() {
	titleFormText=(TextView) GoalEdit.this.findViewById(R.id.form_goal);
	idGoalText=(EditText) findViewById(R.id.id_goal);
	isOwnGoal=(CheckBox) findViewById(R.id.is_own);
	isOwnGoal.setOnClickListener(new OnClickListener() {
	    /**
	     * In caso di autogol vanno caricati i giocatori dell'altra squadra
	     */
	    @Override
	    public void onClick(View v) {
		int squadra_selected=teamSpinner.getSelectedItemPosition()+1;
		int squarda=squadra_selected;
		if (isOwnGoal.isChecked()) {
		    squarda=(squadra_selected==1) ? 2 : 1;
		}
		Cursor playerCur=GoalEdit.this.dbHelper.getAllPlayers(cronaca, squarda);
		SimpleCursorAdapter playerAdapter=new SimpleCursorAdapter(GoalEdit.this,
		    android.R.layout.simple_spinner_item, playerCur, new String[]{DbConst.players.KEY_NAME },
		    new int[]{android.R.id.text1 });
		playerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		playerSpinner.setAdapter(playerAdapter);
	    }
	});
	playerSpinner=(Spinner) findViewById(R.id.player_goal);
	teamSpinner=(Spinner) findViewById(R.id.team_goal);
	ArrayAdapter<CharSequence> teamAdapter=new ArrayAdapter<CharSequence>(this,
	    android.R.layout.simple_spinner_item);
	teamAdapter.add(team1Name);
	teamAdapter.add(team2Name);
	teamSpinner.setAdapter(teamAdapter);
	TeamGoalItemListener teamListener=new TeamGoalItemListener(this);
	teamSpinner.setOnItemSelectedListener(teamListener);
	halfSpinner=(Spinner) findViewById(R.id.half);
	ArrayAdapter<CharSequence> halfAdapter=ArrayAdapter.createFromResource(this, R.array.halfs,
	    android.R.layout.simple_spinner_item);
	halfSpinner.setAdapter(halfAdapter);
	timeText=(EditText) findViewById(R.id.min);
	griglia=(ListView) findViewById(R.id.gridview);
	griglia.setOnItemClickListener(new OnItemClickListener() {

	    @Override
	    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		Cursor c=GoalEdit.this.dbHelper.recuperaGoal(id);
		if (c.moveToFirst()) {
		    GoalEdit.this.titleFormText.setText(getString(R.string.edit_goal));
		    GoalEdit.this.isOwnGoal.setSelected(c.getInt(c.getColumnIndex(DbConst.goals.KEY_TEAM))==1);
		    GoalEdit.this.halfSpinner.setSelection(c.getInt(c.getColumnIndex(DbConst.goals.KEY_HALF))-1);
		    GoalEdit.this.teamSpinner.setSelection(c.getInt(c.getColumnIndex(DbConst.goals.KEY_TEAM))-1);
		    GoalEdit.this.playerSpinner.setSelection(recuperaPosizionePlayer(c.getLong(c
			.getColumnIndex(DbConst.goals.KEY_PLAYER))));
		    GoalEdit.this.idGoalText.setText(Long.toString(id));
		    GoalEdit.this.timeText.setText(c.getString(c.getColumnIndex(DbConst.goals.KEY_MIN)));
		}
	    }

	    private int recuperaPosizionePlayer(long idPlayer) {
		SimpleCursorAdapter sa=(SimpleCursorAdapter) GoalEdit.this.playerSpinner.getAdapter();
		for (int pos=0; pos<DbConst.players.MAX_NUMBER; pos++) {
		    if (sa.getItemId(pos)==idPlayer) {
			return pos;
		    }
		}
		return -1;
	    }
	});
    }

    public void salva(View view) {
	saveState();
	GoalEdit.this.halfSpinner.setSelection(0);
	GoalEdit.this.teamSpinner.setSelection(0);
	GoalEdit.this.playerSpinner.setSelection(0);
	GoalEdit.this.idGoalText.setText("");
	GoalEdit.this.timeText.setText("");
	titleFormText.setText(getString(R.string.new_subst));
	fillData();
    }

    private void saveState() {
	long player=playerSpinner.getSelectedItemId();
	String rowId=idGoalText.getText().toString();
	boolean isAuto=isOwnGoal.isChecked();
	int team=teamSpinner.getSelectedItemPosition()+1;
	int half=halfSpinner.getSelectedItemPosition()+1;
	String min=timeText.getText().toString();
	if (rowId.equals("")) {
	    dbHelper.insertGoal(player, team, half, min, cronaca, isAuto);
	}
	else {
	    dbHelper.updateGoal(Long.parseLong(rowId), player, team, half, min, cronaca, isAuto);
	}
	Toast t=Toast.makeText(this, getString(R.string.just_saved), Toast.LENGTH_LONG);
	t.show();
    }
}
